import logo from '@/assets/logo.png'
import './index.scss'
import { Form, Input, Button, Checkbox, message } from 'antd'
import { UserOutlined, LockOutlined } from "@ant-design/icons"
import { useDispatch } from 'react-redux'
import { loginAction } from '@/store/actions/user'
import { useHistory } from 'react-router-dom'


const loginRules = [{
    required: true,
    message: '请输入手机号'
}, {
    pattern: /^1[3-9]\d{9}$/,
    message: '手机号格式不正确'
}]
const codeRules = [{
    required: true,
    message: '请输入验证码'
}, {
    pattern: /^\d{6}$/,
    message: '验证码格式不正确'
}]

const isArgeeRules = [{
    validator(rule, value) {
        return value ? Promise.resolve() : Promise.reject(new Error("请勾选我已阅读并同意"))
    }
}]

const Login = () => {
    const history = useHistory()
    const dispatch = useDispatch()
    const onFinish = async (values) => {
        try {
            await dispatch(loginAction(values)) // 派发actions
            message.success('登录成功')
            history.replace(history.location?.state?.from || "/home") // 登录成功进行跳转
        } catch (error) {
            message.error('登录失败')
        }
    }

    return (
        <div className="login">
            <div className="login-container">
                <img className="login-logo" src={logo} alt="" />
                {/* 登录表单 */}
                <Form size="large" validateTrigger='onBlur' onFinish={onFinish} initialValues={{
                    mobile: 13911111111,
                    code: '246810',
                    isAgree: true
                }}>
                    <Form.Item rules={loginRules} name="mobile" >
                        <Input prefix={<UserOutlined />} placeholder="请输入手机号" />
                    </Form.Item>
                    <Form.Item rules={codeRules} name="code">
                        <Input prefix={<LockOutlined />} placeholder="请输入验证码" />
                    </Form.Item>
                    <Form.Item name="isAgree" rules={isArgeeRules} valuePropName="checked">
                        <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType='submit' block>
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div >
    )
}

export default Login